<?php


namespace Cumulon\Service\History;

use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Model;

abstract class BaseModel extends Model
{
    protected static function boot()
    {
        parent::boot();

        // 发送日志域名
        $http_url = config('yduserservice.http_history_url');

        /**
         * Handle the user "saving/updating" event.
         */
        static::saved(function ($model) use ($http_url){
            // 更新或者插入后的数据
            $now_data = $model->getAttributes();
            // 获取更新前的数据
            $prior_data = $model->getRawOriginal();
            $basic_data = self::Basic();

            // 判断是否新增
            if($prior_data){
                if(count($model->getDirty())>0){       // 模型是否修改
                    $result = [ 'prior_data'=>$prior_data, 'now_data'=>$now_data, 'basic_data'=>$basic_data, 'history_type' => $basic_data['request_type'] ];
                    HttpHistoryPodcast::dispatch(json_encode($result), $http_url);
                }
            }else{   // 新增
                $result = [ 'now_data'=>$now_data, 'basic_data'=>$basic_data, 'history_type' => $basic_data['request_type'] ];
                HttpHistoryPodcast::dispatch(json_encode($result), $http_url);
            }
        });

        /**
         *  Handle the user "deleted" event.
         */
        static::deleted(function ($model) use ($http_url) {
            $basic_data = self::Basic();

            $result = ['now_data'=>$model->getAttributes(), 'basic_data'=>$this->$basic_data(), 'history_type' => $basic_data['request_type'] ] ;
            HttpHistoryPodcast::dispatch(json_encode($result), $http_url);
        });

    }

    /**
     * 基础数据
     * @return mixed
     */
    protected static function Basic()
    {
        $request_type = request()->request_type;
        switch ($request_type){
            case "select":
                $request_type_name = '查询操作';
                break;
            case "put":
                $request_type_name = '修改操作';
                break;
            case "delete":
                $request_type_name = '删除操作';
                break;
            case "post":
                $request_type_name = '添加操作';
                break;
            default:
                $request_type_name = '';
                break;
        }
        $result['request_type'] = $request_type_name;
        $result['method']       = request()->getMethod();
        $result['ip']           = request()->getClientIp();
        $result['param']        = request()->all();
        $result['time']         = date('Y-m-d',time());
        $result['url']          = request()->getUri();
        $result['pathinto']     = request()->getPathInfo();
        $result['path']         = request()->path();
        $result['routeName']    = request()->route()->getName();
        $result['user_data']    = request()->user();
        return $result;
    }

}
